<template>
  <div id="manageImagePage">
    <a-flex justify="space-between" style='margin-bottom: 16px'>
      <h2>图片管理</h2>
      <a-space>
        <a-button type="primary" href="/image/add" ghost> + 创建图片</a-button>
        <a-button type="primary" href="/image/add/batch" ghost>+ 批量创建图片</a-button>
      </a-space>
    </a-flex>
    <div class="form">
      <a-form layout="inline" :model="searchParams" @finish="doSearch">
        <a-form-item label="关键词" name="searchText">
          <a-input
            v-model:value="searchParams.searchText"
            placeholder="从名称和简介中搜索"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="类型" name="category">
          <a-auto-complete
            v-model:value="searchParams.category"
            placeholder="请输入类型"
            :options="categoryOptions"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="searchParams.tags"
            mode="tags"
            :options="tagOptions"
            placeholder="请输入标签"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="审核状态" name="reviewStatus">
          <a-select
            v-model:value="searchParams.reviewStatus"
            :options="IMAGE_REVIEW_STATUS_OPTIONS"
            placeholder="请输入审核状态"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-space wrap>
            <a-button :icon="h(SearchOutlined)" type="primary" html-type="submit">搜索</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="handleTableChange"
      :scroll="{ x: 'max-content' }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <a-image :src="record.url + '?x-oss-process=image/format,webp'" :width="120" />
        </template>
        <!-- 标签 -->
        <template v-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">{{ tag }}</a-tag>
          </a-space>
        </template>
        <!-- 图片信息 -->
        <template v-if="column.dataIndex === 'imgInfo'">
          <div v-if="record.imgFormat">格式：{{ record.imgFormat }}</div>
          <div v-if="record.imgWidth">宽度：{{ record.imgWidth }}</div>
          <div v-if="record.imgHeight">高度：{{ record.imgHeight }}</div>
          <div v-if="record.imgScale">宽高比：{{ record.imgScale }}</div>
          <div v-if="record.imgSize">大小：{{ (record.imgSize / 1024).toFixed(2) }}KB</div>
        </template>
        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'reviewInfo'">
          <div>审核状态：{{ IMAGE_REVIEW_STATUS_MAP[record.reviewStatus] }}</div>
          <div v-if="record.reviewMessage">审核信息：{{ record.reviewMessage }}</div>
          <div v-if="record.reviewerId">审核人：{{ record.reviewerId }}</div>
          <div v-if="record.reviewTime">
            审核时间：{{ dayjs(record.reviewTime).format('YYYY-MM-DD HH:mm:ss') }}
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space direction="vertical">
            <a-button
              v-if="record.reviewStatus !== IMAGE_REVIEW_STATUS_ENUM.PASS"
              type="link"
              @click="doReview(record, IMAGE_REVIEW_STATUS_ENUM.PASS)">
              审核通过
            </a-button>
            <a-button type="link" :href="`/image/add?id=${record.id}`" target="_blank">
              编辑
            </a-button>
            <a-button
              v-if="record.reviewStatus !== IMAGE_REVIEW_STATUS_ENUM.REJECT"
              type="link" danger
              @click="doReview(record, IMAGE_REVIEW_STATUS_ENUM.REJECT)">
              审核不通过
            </a-button>
            <a-popconfirm
              title="是否确认删除图片?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="doDelete(record.id)"
              @cancel="cancel">
              <a-button type="link" danger> 删除 </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref, h } from 'vue'
import {
  deleteImageUsingPost,
  listImageByPageUsingPost,
  listImageTagCategoryUsingGet, reviewImageUsingPost
} from '@/api/imageController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { SearchOutlined } from '@ant-design/icons-vue'
import {
  IMAGE_REVIEW_STATUS_ENUM,
  IMAGE_REVIEW_STATUS_MAP,
  IMAGE_REVIEW_STATUS_OPTIONS
} from '@/constants/image.ts'

const columns = [
  {
    title: '图片',
    dataIndex: 'url',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'category',
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '图片信息',
    dataIndex: 'imgInfo',
  },
  {
    title: '审核信息',
    dataIndex: 'reviewInfo',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 用户数据列表
const dataList = ref([])
const total = ref(0)

// 获取数据（分页重置）
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}
// 搜索条件
const searchParams = reactive<API.ImageQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'desc',
})
// 获取数据
const fetchData = async () => {
  const res = await listImageByPageUsingPost({
    ...searchParams,
    nullSpaceId : true
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records
    total.value = res.data.data.total
  } else {
    dataList.value = []
    total.value = 0
    message.error('获取数据失败，' + res.data.message)
  }
}

// 分页
const handleTableChange = (pagination: any) => {
  searchParams.current = pagination.current
  searchParams.pageSize = pagination.pageSize
  fetchData()
}
// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`,
  }
})

// 获取标签和分类选项
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])
const getTagCategoryOptions = async () => {
  const res = await listImageTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // 转换成下拉选项组件接受的格式
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('加载选项失败，' + res.data.message)
  }
}

// 处理图片审核状态
const doReview = async (record: API.Image, reviewStatus: number) => {
  const reviewMessage = reviewStatus === IMAGE_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : '管理员操作拒绝'
  const res = await reviewImageUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage,
  })
  if (res.data.code === 0) {
    message.success('审核操作成功')
    // 重新获取列表
    fetchData()
  } else {
    message.error('审核操作失败，' + res.data.message)
  }
}

// 删除图片
const doDelete = async (id: Number) => {
  var res = await deleteImageUsingPost({
    id: id,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('删除成功')
    fetchData()
  } else {
    message.error('删除失败，' + res.data.message)
  }
}

// 取消删除图片
const cancel = (e: MouseEvent) => {
  console.log(e);
  message.error('取消删除图片！');
};

// 页面加载的时候请求一次
onMounted(() => {
  fetchData()
  getTagCategoryOptions()
})
</script>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}

#manageImagePage .form {
  margin-bottom: 24px;
}
</style>
